package megrez.mail.sender.component.template;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import megrez.mail.sender.common.MailSenderException;

/**
 * Freemarker模板处理
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Component
public class FreemarkerTemplageProcess implements TemplateProcess {
    @Autowired
    private FreeMarkerConfigurer configurer;

    private static AtomicInteger counter = new AtomicInteger();

    @Override
    public String render(String templateValue, Map<String, Object> params) {
        Configuration configuration = configurer.getConfiguration();
        try {
            Template template = new Template(String.valueOf(counter.incrementAndGet()), templateValue, configuration);
            return FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
        } catch (IOException | TemplateException e) {
            throw new MailSenderException(e);
        }
    }

}
